package com.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.server.constant.RedisKey;
import com.server.constant.enyms.BaseStatusEnums;
import com.server.entity.UpmsPermission;
import com.server.entity.UpmsRole;
import com.server.entity.UpmsUser;
import com.server.exception.OperationFailException;
import com.server.mapper.UpmsUserMapper;
import com.server.param.UpmsUserVo;
import com.server.service.IUpmsUserPermissionService;
import com.server.service.IUpmsUserRoleService;
import com.server.service.IUpmsUserService;
import com.server.component.RedisUtil;
import com.server.util.Result;
import com.server.vo.upms.login.LoginVo;
import com.server.vo.upms.user.UserInfo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户 服务实现类
 * </p>
 *
 * @author
 * @since 2020-04-03
 */
@Service
@AllArgsConstructor
public class UpmsUserServiceImpl extends ServiceImpl<UpmsUserMapper, UpmsUser> implements IUpmsUserService {

	private IUpmsUserPermissionService upmsUserPermissionService;
	private IUpmsUserRoleService upmsUserRoleService;
	private RedisUtil redisUtil;
	/**
	 * 新增
	 *
	 * @author
	 * @Date 2020-04-03
	 */
	@Override
	@Transactional(rollbackFor = {Exception.class})
	public Result add(UpmsUserVo vo){
		//先判断下账户名是否存在
		UpmsUser user = getOne(new QueryWrapper<UpmsUser>().lambda().eq(UpmsUser::getUsername,vo.getUsername()).last("limit 1"));
		if(user!=null){
			return Result.error(HttpStatus.HTTP_INTERNAL_ERROR,"该账号用户名已存在");
		}
		user = new UpmsUser();
		String salt = UUID.randomUUID().toString().replaceAll("-", "");
		BeanUtil.copyProperties(vo,user);
		user.setSalt(salt);
//		//如果设置了密码
		if(StrUtil.isNotBlank(user.getPassword())){
			user.setPassword(SecureUtil.md5(vo.getPassword() + salt));
		}else {
			user.setPassword(SecureUtil.md5("123456" + salt));
		}
		if(save(user)){
			return Result.ok("操作成功");
		}

		return Result.error("操作失败");
	}

	/**
	 * 批量删除
	 *
	 * @author
	 * @Date 2020-04-03
	 */
	@Override
	@Transactional(rollbackFor = {Exception.class})
	public Boolean delete(String idsStr){
		String [] ids =idsStr.split(",");
		if(ids.length>0){
			List<String> resultList= new ArrayList<>(Arrays.asList(ids));
			if(this.baseMapper.deleteBatchIds(resultList)<=0){
				return false;
			}
		}
		return true;
	}

	/**
	 * 更新
	 *
	 * @author
	 * @Date 2020-04-03
	 */
	@Override
	@Transactional(rollbackFor = {Exception.class})
	public Result update(UpmsUserVo vo){
		//先判断下账户名是否存在
		UpmsUser user = this.baseMapper.selectById(vo.getUserId());
		if(user==null){
			return Result.error(HttpStatus.HTTP_INTERNAL_ERROR,"找不到该账号记录");
		}
		user.setRealName(vo.getRealName());
  		user.setAvatar(vo.getAvatar());
		user.setPhone(vo.getPhone());
		user.setEmail(vo.getEmail());
		user.setSex(vo.getSex());
		user.setLocked(vo.getLocked());
		user.setEnable(vo.getEnable());
 		if(this.baseMapper.updateById(user)>0){
			return Result.ok("操作成功");
		}
		return Result.error("操作失败");
	}

	/**
	 * 根据id查询详情
	 *
	 * @author
	 * @Date 2020-04-03
	 */
	@Override
	public UpmsUser findById(String id){
		return this.baseMapper.selectById(id);
	}


	/**
	 * 查询分页数据
	 *
	 * @author
	 * @Date 2020-04-03
	 */
	@Override
	public Result<List<UpmsUser>> findPage(Page<UpmsUser> page, QueryWrapper<UpmsUser> q){

		return Result.createResult(this.baseMapper.selectPage(page,q));
	}

	@Override
	@Transactional(rollbackFor = {Exception.class})
	public Result enable(String idsStr, Integer enable) {
		String [] ids = idsStr.split(",");
		for (String id:ids) {
			UpmsUser user = getById(Integer.parseInt(id));
			if(user!=null){
				user.setEnable(enable);
				if(!updateById(user)){
					throw new OperationFailException("禁用失败");
				}
			}
 		}
		return Result.ok("操作成功");
	}

    @Override
	@Transactional(rollbackFor = Exception.class)
    public Result<UserInfo> login(LoginVo vo) {
		/*根据用户名查询用户*/
		UpmsUser user = this.baseMapper.selectOne(new QueryWrapper<UpmsUser>().lambda().eq(UpmsUser::getUsername,vo.getUsername()));
		if(user==null){
			return Result.error(HttpStatus.HTTP_UNAUTHORIZED,"用户名或密码错误");
		}
		/*验证密码是否正确*/
		if(!user.getPassword().equals(SecureUtil.md5(vo.getPassword()+user.getSalt()))){
			return Result.error(HttpStatus.HTTP_UNAUTHORIZED,"用户名或密码错误");
		}
		if (user.getEnable().intValue() == BaseStatusEnums.DISABLE.getValue()) {
			return Result.error(HttpStatus.HTTP_UNAUTHORIZED, "该用户已被禁用");
		}
		/*删除以前老token*/
		if (user.getToken() != null) {
			redisUtil.del(RedisKey.ADMIN_USER+":"+user.getToken());
		}
		/*生成新token*/
		String token = SecureUtil.md5(user.getUsername() + new Date().getTime());
		if (token.length() > 32) {
			token = token.substring(0, 32);
		}
		user.setToken(token);
		this.baseMapper.updateById(user);
		UserInfo userInfo = new UserInfo();
		userInfo.setUpmsUser(user);
		List<UpmsPermission>  upmsUserPermissionList =upmsUserPermissionService.findPermissionByUserId(user.getUserId());
		if(upmsUserPermissionList!=null){
			Map<Integer, List<UpmsPermission>> zoneByParentIdMap = upmsUserPermissionList.stream().collect(Collectors.groupingBy(UpmsPermission::getPid));
			upmsUserPermissionList.forEach(zone->zone.children = zoneByParentIdMap.get(zone.getPermissionId()));
			List<UpmsPermission> menu =	upmsUserPermissionList.stream().filter(v -> v.getPid().equals(0)).collect(Collectors.toList());
			userInfo.setPermissions(menu);
		}
		List<UpmsRole> upmsUserRoleList = upmsUserRoleService.findByUserId(user.getUserId());
		userInfo.setRoles(upmsUserRoleList);

		redisUtil.set(RedisKey.ADMIN_USER+":"+token,userInfo);
		userInfo.setPermissions(null);
		return Result.returnData(userInfo);
    }

}
